package com.d2rv.collision;

import com.d2rv.settings.Settings;
import java.io.File;
import processing.core.PApplet;
import processing.core.PVector;

/**
 * This class is a manager for the class collision 
 * @author Darrieutort A., Dupouy A., Rossignol L., Van Poucke A.
 */
public class CollisionManager {

    private Collision collision;
    private int offsetcollision;
    private PVector[] polygone;
    private PApplet parent;

    /**
     * Default constructor.
     * @param parent The current application
     */
    public CollisionManager(PApplet parent) {
        Settings settings = Settings.getInstance();
        this.collision = new Collision(parent, parent.dataPath("models" + File.separator + "city" + File.separator + settings.citymapname()));
        this.offsetcollision = 2;
        this.polygone = new PVector[8];
        this.parent = parent;
    }

    /**
     * Decides if the point at x,y is in the circle xCenter yCenter.
     * @param x The x coordinate of the point to test
     * @param y The y coordinate of the point to test
     * @param xCenter The x coordinate of the center of the circle
     * @param yCenter The y coordinate of the center of the circle
     * @return true if the point at (x, y) is in the circle of center (xCenter yCenter).
     */
    public boolean isInCircle(int x, int y, int xCenter, int yCenter) {
        return (((x - xCenter) * (x - xCenter)
                + (y - yCenter) * (y - yCenter)) <= this.offsetcollision);
    }

    /**
     * Decides if the position of the user will enter in a collision zone with the next move
     * @param position The next position of the user
     * @return true if the next move of the user is in a collision zone, false if not
     */
    public boolean testCollision(PVector position) {
        this.polygone[0] = new PVector(position.x, position.y + this.offsetcollision);
        this.polygone[1] = new PVector(position.x + this.offsetcollision / 2, position.y + this.offsetcollision / 2);
        this.polygone[2] = new PVector(position.x + this.offsetcollision, position.y);
        this.polygone[3] = new PVector(position.x + this.offsetcollision / 2, position.y - this.offsetcollision / 2);
        this.polygone[4] = new PVector(position.x, position.y - offsetcollision);
        this.polygone[5] = new PVector(position.x - (offsetcollision / 2), position.y - (offsetcollision / 2));
        this.polygone[6] = new PVector(position.x - this.offsetcollision, position.y);
        this.polygone[7] = new PVector(position.x - (offsetcollision / 2), position.y + (offsetcollision / 2));

        for (int i = 0; i < 8; i++) { 
            if (this.collision.getColorAt((int)this.polygone[i].x, (int) this.polygone[i].y, parent) < 255) {
                return true;
            }
        }
        
        return false;
    }
}